package com.yuyu;

import com.alibaba.fastjson.JSON;
import com.yuyu.bean.Data;
import com.yuyu.bean.Handler;
import com.yuyu.bean.Param;
import com.yuyu.bean.View;
import com.yuyu.config.ConfigEnum;
import com.yuyu.helper.BeanHelper;
import com.yuyu.helper.ConfigHelper;
import com.yuyu.helper.ControlerHelper;
import com.yuyu.util.CodecUtil;
import com.yuyu.util.ReflectionUtil;
import com.yuyu.util.StreamUtile;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Array;
import java.lang.reflect.Method;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * 请求转发器
 * author:yuyu
 * Date:2018/10/21
 * Time:22:58
 */
@WebServlet(urlPatterns = "/*",loadOnStartup = 0)
public class DispatcherServlet extends HttpServlet{

    @Override
    public void init(ServletConfig config) throws ServletException {
        // 初始化Helper类
        HelperLoader.init();
        // 获取ServletContext对象（用于注册Servlet）
        ServletContext servletContext = getServletConfig().getServletContext();
        // 注册处理JSP的Servlet
        ServletRegistration jspServlet = servletContext.getServletRegistration("jsp");
        jspServlet.addMapping(ConfigEnum.APP_JSP_PATH.getName());
        // 注册处理静态资源的默认Servlet
        ServletRegistration defaultServlet = servletContext.getServletRegistration("default");
        defaultServlet.addMapping(ConfigEnum.APP_ASSET_PATH.getName());
        super.init(config);
    }

    @Override
    public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        String reqestMethod = req.getMethod().toLowerCase();
        String pathInfo = req.getPathInfo();

        // 获取请求处理器
        Handler handler = ControlerHelper.getHandler(reqestMethod, pathInfo);
        if (handler != null){
            //
            Class<?> controllerClass = handler.getControllerClass();
            Object controllerBean = BeanHelper.getBean(controllerClass);
            HashMap<String, Object> paramMap = new HashMap<String, Object>();
            Enumeration<String> parameterNames = req.getParameterNames();
            while (parameterNames.hasMoreElements()){
                String paramName = parameterNames.nextElement();
                String paramValue = req.getParameter(paramName);
                paramMap.put(paramName,paramValue);
            }
            String body = CodecUtil.doCodeURL(StreamUtile.getString(req.getInputStream()));
            if (StringUtils.isNotEmpty(body)){
                String[] params = StringUtils.split(body, "&");
                if (ArrayUtils.isNotEmpty(params)){
                    for (String param : params){
                        String[] array = StringUtils.split(param, "=");
                        if (ArrayUtils.isNotEmpty(array) && array.length == 2){
                            paramMap.put(array[0],array[1]);
                        }

                    }

                }
            }
            Param param = new Param(paramMap);
            Method requestMethod = handler.getRequestMethod();
            Object result = ReflectionUtil.invokeMethod(controllerBean, requestMethod, param);

            // 处理requestMethod返回值
            if (result instanceof View){
                // 返回jsp页面
                View view = (View) result;
                String path = view.getPath();
                if (StringUtils.isNotEmpty(path)){
                    if (path.startsWith("/")){
                        res.sendRedirect(req.getContextPath() +path);
                    }else {
                        Map<String, Object> model = view.getModel();
                        for (Map.Entry<String,Object> entry:model.entrySet()){
                            req.setAttribute(entry.getKey(),entry.getValue());
                        }
                         req.getRequestDispatcher(ConfigEnum.APP_JSP_PATH.getName()+path).forward(req,res);
                    }
                }
            }else if (result instanceof Data){
                // 返回JSON数据
                Data data = (Data) result;
                Object model = data.getModel();
                if (model != null){
                    res.setContentType("application/json");
                    res.setCharacterEncoding("UTF-8");
                    PrintWriter writer = res.getWriter();
                    writer.write(JSON.toJSONString(model));
                    writer.flush();
                    writer.close();
                }
            }
        }
    }
}
